package com.leyou.service;

import com.leyou.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Arrays;
import java.util.List;

/**
 * 文件上传
 */
@Service
public class UploadService {

    private static final Logger logger = LoggerFactory.getLogger(UploadService.class);
    /*定义文件类型*/
    private static final List<String> CONTENT_TYPES = Arrays.asList("image/jpeg","image/gif");
    public String upload(MultipartFile file) throws Exception {
        if(file.isEmpty()){
            logger.info("文件是空的：{}",file);
            throw new BusinessException("文件不能为空");
        }
        // 校验文件类型
        if(!CONTENT_TYPES.contains(file.getContentType())){
            logger.info("文件类型不合法：{}",file.getContentType());
            throw new BusinessException("文件类型不合法");
        }

        // 获取文件名
        String originalFilename = file.getOriginalFilename();

        // 校验文件内容
        BufferedImage image = ImageIO.read(file.getInputStream());
        if(image == null){
            logger.info("文件内容不合法：{}",originalFilename);
            throw new BusinessException("文件类内容不合法");
        }
        // 保存到服务器
        file.transferTo(new File("D:/leyou/"+originalFilename));
        return "http://image.leyou.com/"+originalFilename;
    }
}
